package com.qyhl.webtv.module_news.news.union.town.addmeeting;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.view.MotionEventCompat;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.gyf.immersionbar.ImmersionBar;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.qyhl.cloud.webtv.module_news.R;
import com.qyhl.cloud.webtv.module_news.R2;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.basiclib.utils.dialog.LoadingDialog;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.UpTokenBean;
import com.qyhl.webtv.commonlib.entity.act.UploadBean;
import com.qyhl.webtv.commonlib.utils.qiniu.QiniuUpload;
import com.qyhl.webtv.commonlib.utils.qiniu.UploadResultListener;
import com.qyhl.webtv.commonlib.utils.view.imagebrowser.MNImageBrowser;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import es.dmoral.toasty.Toasty;

/**
 * Created by qyhl on 2018/3/6.
 * 添加留言
 */

@Route(path = ARouterPathConstant.ADD_MEETING)
public class AddMeetingActivity extends BaseActivity implements AddMeetingContract.AddMeetingView {


    @BindView(R2.id.add_cancel)
    TextView addCancel;
    @BindView(R2.id.add_submit)
    ImageView addSubmit;
    @BindView(R2.id.content)
    EditText mContent;
    @BindView(R2.id.add_circle_image)
    RecyclerView addCircleImage;
    @BindView(R2.id.video_cover_img)
    ImageView videoCoverImg;
    @BindView(R2.id.video_image_delete)
    ImageView videoImageDelete;
    @BindView(R2.id.video_cover_layout)
    FrameLayout videoCoverLayout;
    @BindView(R2.id.add_video_img)
    ImageView addVideoImg;
    @BindView(R2.id.add_video_layout)
    LinearLayout addVideoLayout;
    @Autowired(name = "id")
    String streetId;

    /**
     * 图片多选
     */
    public static final int CHOOSE_REQUEST = 200;

    /**
     * 图片数据
     */
    private List<LocalMedia> selectedList = new ArrayList<>();
    /**
     * 图片选择适配器
     */
    private RecyclerViewAdatper mImageAdapter;
    /**
     * 空数据
     */
    private LocalMedia addMde;

    private AddMeetingPresenter mPresenter;

    private LoadingDialog.Builder builder;

    /**
     * 上传token
     */
    private UpTokenBean mUpToken;
    @Autowired(name = "rule")
    String rule;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    protected int getContentView() {
        return R.layout.news_activity_add_meeting;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        setDefaultImmerBar();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        mPresenter = new AddMeetingPresenter(this);
        initView();
        setListener();
        //获取上传token
        mPresenter.getToken(false);
    }

    @Override
    protected void setListener() {

    }

    private void initView() {
        builder = new LoadingDialog.Builder(AddMeetingActivity.this);
        builder.setTitle("提交中...");
        builder.setCanceledOnTouchOutside(false);
        builder.setCancelable(true);

        addCircleImage.setVisibility(View.VISIBLE);

        //添加最有一个图片
        addMde = new LocalMedia();
        addMde.setPath("1");
        selectedList.add(addMde);

        addCircleImage.setLayoutManager(new GridLayoutManager(this, 3));
        addCircleImage.setItemAnimator(new DefaultItemAnimator());
        addCircleImage.setAdapter(mImageAdapter = new RecyclerViewAdatper());
    }

    /**
     * 图片多选
     */
    private void chooseImage() {
        PictureSelector.create(AddMeetingActivity.this)
                //仅图片
                .openGallery(PictureMimeType.ofImage())
                //每行显示4张
                .imageSpanCount(4)
                .maxSelectNum(9)
                .selectionMode(PictureConfig.MULTIPLE)
                //允许使用相机
                .isCamera(true)
                //允许预览图片
                .previewImage(true)
                .isZoomAnim(true)
                .compress(true)
                .selectionMedia(selectedList)
                // 小于100kb的图片不压缩
                .minimumCompressSize(100)
                .forResult(CHOOSE_REQUEST);
    }

    private void setListeners() {
        //退出
        addCancel.setOnClickListener(v -> finish());

        //提交
        addSubmit.setOnClickListener(v -> checkData());

    }

    /**
     * 检查数据
     */
    private void checkData() {
        builder.show();

        if (!CommonUtils.getInstance().getUserCheck().equals("1") && CommonUtils.getInstance().getSite() == 217) {
            showToast("用户信息审核中，暂时无法使用该功能！", INFO);
            builder.dismiss();
            return;
        }

        final String content = mContent.getText().toString();
        if (StringUtils.isEmpty(content)) {
            showToast("不能发布空内容", INFO);
            builder.dismiss();
            return;
        }

        if (selectedList != null && selectedList.size() > 1) {
            if (mUpToken == null) {
                mPresenter.getToken(true);
                return;
            }
            List<UploadBean> uploadBeans = new ArrayList<UploadBean>();
            for (int i = 0; i < selectedList.size() - 1; i++) {
                LocalMedia image = selectedList.get(i);
                UploadBean videoCoverBean = new UploadBean();
                videoCoverBean.setType(2);
                videoCoverBean.setPath(image.getCompressPath());
                videoCoverBean.setPostion(0);
                uploadBeans.add(videoCoverBean);
            }
            QiniuUpload.getQiniuUpload().UploadFiles(uploadBeans, mUpToken.getUptoken(), mUpToken.getPrefix(), new UploadResultListener() {
                @Override
                public void uplaodError() {
                    builder.dismiss();
                    showToast("上传图片出错", INFO);
                }

                @Override
                public void uploadSuccess(List<UploadBean> files) {
                    Log.i("addmeeting", "uploadSuccess");
                    StringBuffer stringBuffer = new StringBuffer();
                    for (int i = 0; i < files.size(); i++) {
                        if (i == files.size() - 1) {
                            stringBuffer.append(files.get(i).getUrl());
                        } else {
                            stringBuffer.append(files.get(i).getUrl() + ",");
                        }
                    }
                    mPresenter.addMeeting(streetId, content, "2", stringBuffer.toString());
                }

                @Override
                public void uploadPre(double percent) {

                }
            });
        } else {
            mPresenter.addMeeting(streetId, content, "1", null);
        }
    }

    @Override
    public void addSuccess(String msg) {
        builder.dismiss();
        if (Integer.parseInt(rule) == 1) {
            Toasty.normal(this, msg).show();
            setResult(RESULT_OK);
            finish();
        } else {
            Toasty.normal(this, "发布成功，等待审核！").show();
            finish();
        }

    }

    @Override
    public void addError(String msg) {
        builder.dismiss();
        Toasty.normal(this, msg).show();
    }

    @Override
    public void getTokenSuccess(UpTokenBean data, boolean isUpload) {
        mUpToken = data;
        if (isUpload) {
            checkData();
        }
    }

    @Override
    public void getTokenError(boolean isUpload) {
        if (isUpload) {
            builder.dismiss();
            Toasty.normal(this, "上传失败！").show();
        }
    }


    /**
     * RecyclerViewAdatper
     */
    public class RecyclerViewAdatper extends RecyclerView.Adapter<ViewHolder> {

        RecyclerViewAdatper() {
        }

        @Override
        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.news_item_content_img_list, parent, false);
            return new ViewHolder(view);
        }

        @Override
        public void onBindViewHolder(final ViewHolder holder, final int position) {
            if (selectedList.get(position).getPath().endsWith("1")) {
                holder.deleteView.setVisibility(View.GONE);
                holder.handleView.setImageResource(R.drawable.icon_add_iamge);
                holder.handleView.setOnTouchListener(null);
            } else {
                holder.deleteView.setVisibility(View.VISIBLE);
                holder.deleteView.setTag(position);
                holder.deleteView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (!selectedList.get(selectedList.size() - 1).getPath().endsWith("1")) {
                            selectedList.add(addMde);
                        }
                        int pos = (int) v.getTag();
                        selectedList.remove(pos);
                        mImageAdapter.notifyDataSetChanged();
                    }
                });
                if (position == selectedList.size() - 1) {
                    holder.handleView.setImageResource(R.drawable.icon_add_iamge);
                    holder.handleView.setOnTouchListener(null);
                } else {

                    Glide.with(AddMeetingActivity.this).load(selectedList.get(position).getCompressPath()).into(holder.handleView);
                    holder.handleView.setOnTouchListener((v, event) -> {
                        if (MotionEventCompat.getActionMasked(event) == MotionEvent.ACTION_DOWN) {
                            if (!selectedList.get(selectedList.size() - 1).getPath().endsWith("1")) {
                                selectedList.add(addMde);
                            }
                        }
                        return false;
                    });
                }
            }
        }

        @Override
        public int getItemCount() {
            return selectedList.size();
        }
    }


    /**
     * ViewHolder
     */
    class ViewHolder extends RecyclerView.ViewHolder {
        public ImageView handleView;
        public ImageView deleteView;

        public ViewHolder(View itemView) {
            super(itemView);
            handleView = (ImageView) itemView.findViewById(R.id.content_img);
            deleteView = (ImageView) itemView.findViewById(R.id.image_delete);
            itemView.setOnClickListener(view -> {
                if (selectedList.size() == 0 || !selectedList.get(selectedList.size() - 1).getPath().endsWith("1")) {
                    selectedList.add(addMde);
                }
                if (getLayoutPosition() == selectedList.size() - 1) {
                    //弹出选择菜单
                    selectedList.remove(selectedList.size() - 1);
                    chooseImage();
                } else {

                    ArrayList<String> result = new ArrayList<>();
                    for (int i = 0; i < selectedList.size() - 1; i++) {
                        result.add(selectedList.get(i).getPath());
                    }
                    MNImageBrowser.showImageBrowser(AddMeetingActivity.this, view, getLayoutPosition(), result);

                }
            });
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        List<LocalMedia> resultList;
        switch (requestCode) {
            case CHOOSE_REQUEST:
                resultList = PictureSelector.obtainMultipleResult(data);
                if (resultList != null && resultList.size() > 0) {
                    selectedList.clear();
                    selectedList.addAll(resultList);
                }
                selectedList.add(addMde);
                mImageAdapter.notifyDataSetChanged();
                break;
            default:
                break;
        }
    }
}
